package com.org.redis.bloom;


import java.util.BitSet;

/**
 * 布隆过滤器
 * @author
 */
public class BloomFilter {

    private static int number = 20000;  //要存储的数据量

    private static double fpp = 0.01F;  //所能容忍的错误率

    private  BitSet bitSet = null;

    public BloomFilter() {
        long numBits = optimalNumBits(number,fpp);
        bitSet = new BitSet((int)numBits);
    }


    private void setValue(String key){
        bitSet.set(Math.abs(key.hashCode()));
    }

    private boolean getValue(String key){
        return bitSet.get(Math.abs(key.hashCode()));
    }

    /**
     * 计算容器大小
     * @param number
     * @param fpp
     * @return
     */
    private static long optimalNumBits(int number, double fpp) {
        if (fpp == 0) {
            fpp = Double.MIN_VALUE;
        }
        return (long) (-number * Math.log(fpp) / (Math.log(2) * Math.log(2)));
    }



    public static void main(String[] args) {
        BloomFilter bloomFilter = new BloomFilter();
        bloomFilter.setValue("111");
        bloomFilter.setValue("2222");
        System.out.println(bloomFilter.getValue("111"));
        System.out.println(bloomFilter.getValue("111111"));
        System.out.println(bloomFilter.getValue("111111"));
        System.out.println(bloomFilter.getValue("111111"));
    }
}
